"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 数据库主备节点多个cpu占有率达到90%，主备切换
Create At   : 2022/07/06
Owner       : @li-xin12345
Description :
    1、注入故障：主备数据库节点cpu占有率达到90%
    2、主备切换
    3、清除故障
    4、恢复主备
Expect      :
    1、注入故障成功
    2、switchover成功
    3、清除故障成功
    4、恢复主备
History     :
    Modified by @li-xin12345 2023/2/7:修改注入故障断言信息
"""
import os
import unittest
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import RestartDbCluster
from yat.test import Node
from yat.test import macro

Primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_sh.get_node_num(), '单机环境不执行')
class Dbsys(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.primary_root = Node('PrimaryRoot')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.standby_root = Node('Standby1Root')
        self.constant = Constant()
        self.common = Common()

    def test_dbsys(self):
        try:
            text = "-----step1:注入故障：主备数据库节点cpu占有率达到90%，" \
                   "top查询cpu多核占用情况;expect:注入故障成功-----"
            self.logger.info(text)
            self.logger.info("-----获取cpu个数-----")
            shell_cmd = "cat /proc/cpuinfo |grep 'processor'|wc -l"
            self.logger.info(shell_cmd)
            cpu_num = self.primary_root.sh(shell_cmd).result()
            self.logger.info('cpu个数为:' + cpu_num)
            self.logger.info("-----主节点注入故障-----")
            cfe_inject_cmd = f"rCPU_Overloadap(cpuid1,cpuid2) " \
                f"values(0,{int(cpu_num) - 1})"
            pri_inject_res = self.common.cfe_inject(self.primary_root,
                                                    cfe_inject_cmd)
            self.logger.info(pri_inject_res)
            self.assertIn(self.constant.cfe_inject_rcpu_overloadau_success_msg,
                          pri_inject_res, '执行失败' + text)
            top_cmd = f"export TERM=dumb;top -b -n 1 -o %CPU"
            self.logger.info(top_cmd)
            top_msg_pri = self.primary_root.sh(top_cmd).result()
            self.logger.info(top_msg_pri)
            self.logger.info("-----备节点注入故障-----")
            sta_inject_res = self.common.cfe_inject(self.standby_root,
                                                    cfe_inject_cmd)
            self.logger.info(sta_inject_res)
            self.assertIn(self.constant.cfe_inject_rcpu_overloadau_success_msg,
                          pri_inject_res, '执行失败' + text)
            top_msg_sta = self.standby_root.sh(top_cmd).result()
            self.logger.info(top_msg_sta)

            text = "-----step2:主备切换，expect:主备切换成功-----"
            self.logger.info(text)
            switchover_msg = self.standby_sh.executeGsctl(
                'switchover', self.constant.SWITCH_SUCCESS_MSG)
            self.assertTrue(switchover_msg, '执行失败:' + text)
            refresh_msg = self.standby_sh.exec_refresh_conf()
            self.assertTrue(refresh_msg, '执行失败:' + text)
            status = self.primary_sh.getDbClusterStatus("status")
            self.logger.info(status)
            self.assertTrue(status, '执行失败:' + text)
        finally:
            text = "-----step3:清除故障，expect:清除故障成功-----"
            self.logger.info(text)
            cfe_clean_cmd = f"rCPU_Overloadap"
            cfe_clean_res = self.common.cfe_clean(self.primary_root,
                                                  cfe_clean_cmd)
            self.logger.info(cfe_clean_res)
            self.assertIn(self.constant.cfe_inject_rcpu_overloadau_cleaned_msg,
                          cfe_clean_res, '执行失败' + text)

    def tearDown(self):
        text = "-----step4:恢复主备，expect:恢复主备成功-----"
        self.logger.info(text)
        switchover_msg = self.primary_sh.executeGsctl(
            'switchover', self.constant.SWITCH_SUCCESS_MSG)
        refresh_msg = self.primary_sh.exec_refresh_conf()
        status = self.primary_sh.getDbClusterStatus("status")
        self.logger.info(status)
        self.logger.info('-----断言tearDown-----')
        self.assertTrue(switchover_msg, '执行失败:' + text)
        self.assertTrue(refresh_msg, '执行失败:' + text)
        self.assertTrue(status, '执行失败:' + text)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
